"""LLM API集成模块"""
import requests
import json
import logging
from typing import Dict, List, Optional

class Chat:
    """聊天类，用于处理LLM API交互"""

    API_URL = "https://api.siliconflow.cn/v1/chat/completions"
    MODEL_NAME = "Qwen/Qwen2.5-72B-Instruct-128K"

    def __init__(self, api_key: str, prompt: str):
        """初始化Chat实例
        
        Args:
            api_key (str): API密钥
            prompt (str): 系统提示词
        """
        self.api_key = api_key
        self.system_prompt = prompt
        self.chat_history: Dict[str, List[Dict[str, str]]] = {}

    def chat(self, user_message: str, user_id: str = "default") -> str:
        """发送消息到LLM并获取响应
        
        Args:
            user_message (str): 用户输入消息
            user_id (str, optional): 用户唯一标识符. 默认为 "default"

        Returns:
            str: 模型的响应消息
        """
        # 初始化新用户的对话历史
        if user_id not in self.chat_history:
            self.chat_history[user_id] = []

        # 构建消息列表
        messages = [
            {"role": "system", "content": self.system_prompt}
        ] + self.chat_history[user_id] + [
            {"role": "user", "content": user_message}
        ]

        # 准备请求数据
        payload = self._prepare_payload(messages)
        headers = self._prepare_headers()

        try:
            response = requests.post(self.API_URL, json=payload, headers=headers)
            response.raise_for_status()
            res_obj = response.json()

            if res_obj.get("code") == 50501:
                logging.warning("API request timeout")
                return "模型请求超时，请稍后再试"

            content = res_obj['choices'][0]['message']['content']

            # 更新对话历史
            self._update_chat_history(user_id, user_message, content)

            logging.info(f"Successfully generated response for user {user_id}")
            return content

        except requests.exceptions.RequestException as e:
            logging.error(f"API request failed: {str(e)}")
            return "抱歉，网络连接出现问题，请稍后再试"

        except (KeyError, json.JSONDecodeError) as e:
            logging.error(f"Failed to parse API response: {str(e)}")
            return "抱歉，服务器返回了无效的响应，请稍后再试"

        except Exception as e:
            logging.error(f"Unexpected error: {str(e)}")
            return "抱歉，我现在无法回复，请稍后再试"

    def _prepare_payload(self, messages: List[Dict[str, str]]) -> Dict:
        """准备API请求的payload
        
        Args:
            messages (List[Dict[str, str]]): 消息列表

        Returns:
            Dict: API请求的payload
        """
        return {
            "model": self.MODEL_NAME,
            "messages": messages,
            "stream": False,
            "max_tokens": 512,
            "stop": ["null"],
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": {"type": "text"},
            "tools": [{
                "type": "function",
                "function": {
                    "description": "<string>",
                    "name": "<string>",
                    "parameters": {},
                    "strict": False
                }
            }]
        }

    def _prepare_headers(self) -> Dict[str, str]:
        """准备API请求的headers
        
        Returns:
            Dict[str, str]: API请求的headers
        """
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def _update_chat_history(self, user_id: str, user_message: str, 
                           assistant_message: str) -> None:
        """更新对话历史
        
        Args:
            user_id (str): 用户唯一标识符
            user_message (str): 用户消息
            assistant_message (str): 助手消息
        """
        self.chat_history[user_id].extend([
            {"role": "user", "content": user_message},
            {"role": "assistant", "content": assistant_message}
        ])

        # 保持历史记录在合理范围内（最近10轮对话）
        if len(self.chat_history[user_id]) > 20:
            self.chat_history[user_id] = self.chat_history[user_id][-20:]

    def clear_history(self, user_id: Optional[str] = None) -> None:
        """清除对话历史
        
        Args:
            user_id (Optional[str]): 用户唯一标识符。如果为None，则清除所有历史
        """
        if user_id is None:
            self.chat_history.clear()
        elif user_id in self.chat_history:
            self.chat_history[user_id] = [] 